#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/3/20 14:36
# @Author  : mazhi
# @Site    :
import sys
from django.conf import settings
import logging

from util.jsonresult import getResult

log = logging.getLogger('db')

class ExceptionMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # 一次性配置和初始化。

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        # 这里写的代码会在视图被调用前执行来处理请求
        response = self.get_response(request)
        # 这里写的代码会在视图调用后执行来处理响应
        # Code to be executed for each request/response after
        # the view is called.

        return response





    """
    错误异常捕获的中间件
    """

    def process_exception(self, request, e):
        """
        程序遇到未捕获的异常，会在此处整理出错误信息，和代码行数
        :param request:
        :param e:
        :return:
        """
        import time
        # if settings.IS_TEST:
        #     return

        errorid = time.time()


        s = [u'错误码:%s' % errorid, u'%s:%s' % (request.method, request.path)]

        s.append(u'出现以下错误：')
        # s.append(traceback.format_exc())
        etype, value, tb = sys.exc_info()
        print(repr(value))
        s.append(repr(e))
        s.append(u'错误代码位置如下：')
        while tb is not None:
            f = tb.tb_frame
            lineno = tb.tb_lineno
            co = f.f_code
            filename = co.co_filename
            name = co.co_name
            s.append(u'File "%s", line %d, in %s' % (filename, lineno, name))
            tb = tb.tb_next
        if not settings.DEBUG:
            log.exception('\n    '.join(s))
            return getResult(False, u'服务器端错误,请联系管理员,错误标记码：%s' % errorid, dialog=2)
        else:
            m = '\n    '.join(s)
            log.exception(m)
            return getResult(False, u'服务器端错误,错误如下：\n%s' % (m), dialog=2)